using NFreeMarker.Template;

namespace NFreeMarker.Core
{
    /**
     * Sequence variable implementation that wraps a string[] with relatively low
     * resource utilization. Warning: it does not copy the wrapped array, so do
     * not modify that after the model was made!
     *
     * @author Daniel Dekany
     * @version $Id: StringArraySequence.java,v 1.2 2004/01/06 17:06:42 szegedia Exp $
     */

    public class StringArraySequence : ITemplateSequenceModel
    {
        private readonly string[] _stringArray;
        private ITemplateScalarModel[] _array;

        /**
         * Warning: Does not copy the argument array!
         */

        public StringArraySequence(string[] stringArray)
        {
            _stringArray = stringArray;
        }

        public ITemplateModel Get(int index)
        {
            if (_array == null)
            {
                _array = new ITemplateScalarModel[_stringArray.Length];
            }
            if (index < 0 || index >= Size())
            {
                    return null;
            }
            ITemplateScalarModel result = _array[index];
            if (result == null)
            {
                result = new SimpleScalar(_stringArray[index]);
                _array[index] = result;
            }
            return result;
        }

        public int Size()
        {
            return _stringArray.Length;
        }
    }
}